import 'package:sptapp/basic/base_info.dart';
import 'package:sptapp/moudle/event_bus.dart';
import 'package:sptapp/moudle/wifi_tool.dart';

import '../api/interface/home_api.dart';
import '../api/interface/user_api.dart';
import '../api/request/response_data.dart';

String avatarPath = '';
Map baseUserInfo = {};
getBaseUserInfo(callBack)async{
  ResponseData res = await UserAPI.getUserInfo();
  if(res.code == 200 && res.data != null){
    WifiTool.getWifiName();
    baseUserInfo = res.data['userInfo'];
    baseUserInfo['equipmentExist'] = res.data['equipmentExist'] ?? false;
    baseUserInfo['networkExist'] = res.data['networkExist'] ?? false;
    baseUserInfo['updateUser'] = res.data['updateUser'] ?? true;
    if(baseUserInfo['nickname'] == null){
      baseUserInfo['nickname'] = '${baseUserInfo['firstName']??''}';
    }
    if(baseUserInfo['nickname'] == null || baseUserInfo['nickname'].toString().isEmpty){
      baseUserInfo['nickname'] = 'user';
    }
    baseUserInfo['avatar'] = baseUserInfo['avatar'] ?? 'assets/home/home_person.png';
    if(avatarPath != null && avatarPath.isNotEmpty){
      baseUserInfo['avatar'] = avatarPath;
    }
    eventBus.fire(UserInfoChange());
  }
  if(callBack!=null){
    callBack();
  }
}

List baseDevices = [];
String? baseDeviceNum;
Map? baseDevice;
getDevicesList(callBack)async{
  ResponseData res = await HomeAPI.selectEquipmentInfo('');
  if(res.code == 200){
    baseDeviceNum = null;
    baseDevice = null;
    baseDevices = res.data ?? [];
    if(baseDevices.isNotEmpty){
      String? num = LocalBaseInfo.getDeviceNum();
      if(num != null){
        for(var item in baseDevices){
          if(item['name'] == null){
            item['name'] = item['sn'];
          }
          if(item['sn'] == num){
            baseDeviceNum = item['sn'];
            baseDevice = item;
            break;
          }
        }
      }
      baseDeviceNum ??= baseDevices[0]['sn'];
      if(baseDeviceNum != null){
        LocalBaseInfo.setDeviceNum(baseDeviceNum!);
      }
      if(baseDevice != null){
        baseDevices.remove(baseDevice);
        baseDevices.insert(0, baseDevice);
      }
      baseDevice = baseDevices[0];
    }else{
      baseDeviceNum = null;
      baseDevice = null;
    }
  }
  if(callBack!=null){
    callBack();
  }
}